import { receiptRecord, reminders } from '@/services/api/api-instruct-record';
import { CheckSquareOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { Button, Col, message, Row } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import { useState } from 'react';

interface RemindersProps {
    id: string;
    type: 'read' | 'receipt';
    isRun: boolean;
}

const Reminders: React.FC<RemindersProps> = ({ id, type, isRun }) => {
    const [dataTree, setDataTreeState] = useState<DataNode[]>();
    const [dataCheckTree, setDataCheckTreeState] = useState<any>();

    const checkTreeKeys = new Array();

    const [createdCombineId, setCreatedCombineIdState] = useState<string>();

    /**
     * 加载组织树请求网络
     */
    const loadData = async () => {
        try {
            const response = await receiptRecord({ id, type: type === 'read' ? 1 : 2 });

            if (response.code === 0) {
                setDataTreeState(readyTreeData(response.data));
                setDataCheckTreeState(checkTreeKeys);
            }
        } catch (error) { }
    };

    /**
     * 预备Tree结构数据
     * @param data
     */
    function readyTreeData(data: Array<UserData.Organization>): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val, idx, array) => {
                // 先检查子节点  
                const children = readyTreeData(val.children as Array<UserData.Organization>);
                // 检查子节点是否有任何被选中  
                const hasSelectedChildren = children.length > 0;

                // 只加入 isView === 0 的节点，且父节点 isView === 0  
                if (val.isView === 0) {
                    // 将当前节点 push 到树数据中  
                    treeData.push({
                        title: val.name,
                        key: val.id,
                        icon: val.isView === 1 ? <CheckSquareOutlined /> : <QuestionCircleOutlined />,
                        isView: val.isView,
                        children: children,
                    });
                    // 如果没有子节点且未选中，则加入 checkTreeKeys  
                    if (children.length === 0 && !val.children) {
                        checkTreeKeys.push(val.id);
                    }
                } else if (hasSelectedChildren) {
                    // 如果子节点有被选中，那么父节点的 isView 必须为 0  

                }
            });
        }

        return treeData;
    }

    return (
        <DrawerForm
            title='一键催办'
            trigger={<Button type='primary'>一键催办</Button>}
            drawerProps={{
                size: 'large',
                // forceRender: true,
                destroyOnClose: true,
                width: '100%',
            }}
            onVisibleChange={(visible) => {
                if (visible) {
                    loadData();
                }
            }}
            onFinish={async () => {
                const res = await reminders({ ids: dataCheckTree, instructId: id })
                if (res.code === 0) {
                    message.success('催办成功')
                } else {
                    message.error('催办失败')
                }
                return true
            }}
        >
            {dataTree && dataTree.length ? (
                <Tree
                    treeData={dataTree}
                    checkedKeys={dataCheckTree}
                    onCheck={(checkedKeys, e) => {
                        const checkKeys = new Array();
                        e.checkedNodesPositions?.forEach((item) => {
                            if (item.node.children?.length === 0) {
                                checkKeys.push(item.node.key);
                            }
                        });
                        console.log(checkKeys);
                        setDataCheckTreeState(checkKeys);
                    }}
                    checkable
                    style={{ width: '100%' }}
                    defaultExpandAll={true}
                    onSelect={(selectedKeys, info) => {
                        if (info.selected && info.node.checked) {
                            console.log('====', selectedKeys, info);
                            setCreatedCombineIdState(info.node.key as string);
                        }
                    }}
                />

            ) : (
                '暂无数据'
            )}
        </DrawerForm>
    );
};

export default Reminders;
